package com.wwy.configuraion;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Properties;

/**
 *对增删改的语句 更新时间
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class UpdateTimeInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        // 获取 SQL 命令
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        // 获取参数
        Object parameter = invocation.getArgs()[1];
        // 字段属于（createtime, createTime, updatetime, updateTime） 且 字段类型是java.util.Date才修改
        if (parameter != null) {
            Date now = new Date();
            Field[] fields = parameter.getClass().getDeclaredFields();
            // 插入SQL
            if (SqlCommandType.INSERT.equals(sqlCommandType)) {
                for (Field field : fields) {
                    if ("createtime".equalsIgnoreCase(field.getName())) {
                        if (field.getType() == Date.class) {
                            field.setAccessible(true);
                            field.set(parameter, now);
                        }
                    }
                    if ("updatetime".equalsIgnoreCase(field.getName())) {
                        if (field.getType() == Date.class) {
                            field.setAccessible(true);
                            field.set(parameter, now);
                        }
                    }
                }
            }

            // 修改SQL
            if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
                for (Field field : fields) {
                    if ("updatetime".equalsIgnoreCase(field.getName())) {
                        if (field.getType() == Date.class) {
                            field.setAccessible(true);
                            field.set(parameter, now);
                        }
                        // 一个对象只会有一个updatetime属性
                        break;
                    }
                }
            }
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
